﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using X.PagedList;
using XbsWebAPI.EntityFrameworkCore;
using XbsWebAPI.EntityFrameworkCore.Entities;
using XbsWebAPI.EntityFrameworkCore.Entities.Enums;

namespace XbsWebAPI.Core.Repositories
{
    /// <summary>
    /// 营位图片领域模型 实现
    /// </summary>
    public class CampImageRepository : ICampImageRepository
    {
        private readonly DataContext _dbContext;

        public CampImageRepository(DataContext dataContext)
        {
            _dbContext = dataContext;
        }

        public CampImage Create(CampImage entity)
        {
            entity.Id = Guid.NewGuid();
            entity.CreationDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            _dbContext.CampImages.Add(entity);
            _dbContext.SaveChanges();

            return entity;
        }

        public Task<CampImage> CreateAsync(CampImage entity)
        {
            entity.Id = Guid.NewGuid();
            entity.CreationDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            _dbContext.CampImages.Add(entity);
            _dbContext.SaveChanges();
            return Task.FromResult(entity);
        }

        public CampImage Delete(Guid id)
        {
            var model = _dbContext.CampImages.FirstOrDefault(x => x.Id == id);
            if (model == null)
                return null;
            _dbContext.Remove(model);
            _dbContext.SaveChanges();

            return model;
        }

        public Task<CampImage> DeleteAsync(Guid id)
        {
            return Task.FromResult(Delete(id));
        }

        public IQueryable<CampImage> Query(Expression<Func<CampImage, bool>> filter)
        {
            var query = _dbContext.CampImages.Where(filter);

            return query;
        }

        public IQueryable<CampImage> AsQueryable()
        {
            var query = _dbContext.CampImages.AsQueryable();

            return query;
        }

        public CampImage QueryById(Guid id)
        {
            return _dbContext.CampImages.FirstOrDefault(x => x.Id == id);
        }

        public CampImage Update(CampImage entity)
        {
            var model = _dbContext.CampImages.FirstOrDefault(x => x.Id == entity.Id);
            if (model == null)
                return null;

            model.UpdateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            _dbContext.CampImages.Update(model);
            _dbContext.SaveChanges();

            return entity;
        }

        public Task<CampImage> UpdateAsync(CampImage entity)
        {
            return Task.FromResult(Update(entity));
        }
    }
}
